import Axios, { AxiosHeaders } from 'axios'
import { getToken } from '../store'
import buildURL from '@/../node_modules/axios/lib/helpers/buildURL.js'
import settle from '@/../node_modules/axios/lib/core/settle.js'

var test = process.env.NODE_ENV === 'development';

test = false;

const baseUrl = test ? 'http://192.168.31.11:52212/private/v1/' : 'https://www.ytad-pep.com/private/v1/';

const axios = Axios.create({
	baseURL: baseUrl,
	timeout: 5000
});

axios.defaults.adapter = function (config : any) {
	const token = getToken();
	const headers : AxiosHeaders = config.headers;

	if (token) {
		headers.set('Authorization', `Bearer ${token}`);
	}

	var url = config.baseURL;

	if (config.url.startsWith('/')) {
		url += config.url.substring(1);
	} else {
		url += config.url;
	}

	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中...'
		})
		
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(url, config.params, config.paramsSerializer),
			header: headers.toJSON(),
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response : any) {
				uni.hideLoading()
				
				settle(resolve, reject, {
					data: response.data,
					status: 200,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				});
				
				if (response.statusCode === 401) {
					uni.showLoading({
						title: '正在跳转至登录界面...'
					})
					
					uni.redirectTo({
						url: '/pages/login/Index',
						complete() {
							uni.hideLoading()
						}
					})
				}
			}
		});
	});
};

// @ts-ignore
uni.$http = axios

uni.$downloadFile = (opts: any) => {
	const token = getToken();
	const headers : any = {};
	
	if (token) {
		headers.Authorization = `Bearer ${token}`;
	}
	
	opts.url = baseUrl + opts.url;
	opts.header = headers;
	
	return uni.downloadFile(opts);
};